package middlewares

import (
	"final-url/entity"
	"net/http"
	"strings"
)

func NewIp(config *entity.Config) func(next http.HandlerFunc) http.HandlerFunc {
	return func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			ip := r.Header.Get("X-Forwarded-For")
			if ip == "" {
				ip = r.RemoteAddr[:strings.Index(r.RemoteAddr, ":")]
			}
			for _, allowedIp := range config.AllowedIps {
				matched := ip == allowedIp
				if !matched && strings.Contains(allowedIp, "*") {
					matched = strings.HasPrefix(ip, allowedIp[:strings.Index(allowedIp, "*")])
				}
				if matched {
					next(w, r)
					return
				}
			}
			http.Error(w, "Forbidden", http.StatusForbidden)
		}
	}
}
